import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface CartItem {
  id: number
  title: string
  content: string
  price: number
  image?: string
  quantity: number
}

export const useCartStore = defineStore('cart', () => {
  const items = ref<CartItem[]>([])
  const totalAmount = ref(0)

  // 从localStorage加载购物车数据
  const loadCartFromStorage = () => {
    const savedCart = localStorage.getItem('cart')
    if (savedCart) {
      items.value = JSON.parse(savedCart)
      calculateTotal()
    }
  }

  // 保存购物车数据到localStorage
  const saveCartToStorage = () => {
    localStorage.setItem('cart', JSON.stringify(items.value))
  }

  // 添加商品到购物车
  const addToCart = (item: Omit<CartItem, 'quantity'>) => {
    const existingItem = items.value.find(i => i.id === item.id)
    if (existingItem) {
      existingItem.quantity++
    } else {
      items.value.push({ ...item, quantity: 1 })
    }
    calculateTotal()
    saveCartToStorage()
  }

  // 从购物车移除商品
  const removeFromCart = (itemId: number) => {
    items.value = items.value.filter(item => item.id !== itemId)
    calculateTotal()
    saveCartToStorage()
  }

  // 更新商品数量
  const updateQuantity = (itemId: number, quantity: number) => {
    const item = items.value.find(i => i.id === itemId)
    if (item) {
      item.quantity = Math.max(0, quantity)
      if (item.quantity === 0) {
        removeFromCart(itemId)
      } else {
        calculateTotal()
        saveCartToStorage()
      }
    }
  }

  // 计算总金额
  const calculateTotal = () => {
    totalAmount.value = Number((items.value.reduce((total, item) => {
      return total + item.price * item.quantity
    }, 0)).toFixed(1))
  }

  // 清空购物车
  const clearCart = () => {
    items.value = []
    totalAmount.value = 0
    saveCartToStorage()
  }

  return {
    items,
    totalAmount,
    addToCart,
    removeFromCart,
    updateQuantity,
    clearCart,
    loadCartFromStorage
  }
})